package com.by.service.goods.impl;

import com.by.bean.goods.Goods;
import com.by.common.crud.BaseServiceImpl;
import com.by.mapper.goods.GoodsMapper;
import com.by.mapper.order.OrderMapper;
import com.by.service.goods.GoodsService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class GoodsServiceImpl extends BaseServiceImpl<Goods, GoodsMapper> implements GoodsService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderMapper orderMapper;

    /**
     * 抢购请求
     * @param id  用户id
     * @param goodsId  商品id
     */
    @Override
    public void toOrder(int id, int goodsId) {
        String msg = id+","+goodsId;
        //向mq队列发送信息
        rabbitTemplate.send("normal-ex", "normal", new Message(msg.getBytes()));
    }

  //  @RabbitListener(queues = {"queue"})
    public void consumer(Message message){

        String msg = new String(message.getBody());
        int id =Integer.parseInt( msg.split(",")[0]);
        int goodsId =Integer.parseInt( msg.split(",")[1]);

        //查询商品信息
        Goods goods = baseMapper.selectById(goodsId);
        //判断商品库存
        int num = goods.getNum();

        if (num == 0) {
            //库存为0
            System.out.println("商品已售完！");
        }

        //判断用户是否买过
        int gid = orderMapper.queryById(id);
        if (gid != 0) {
            //买过
            System.out.println("限购一个！");
        }

        // 库存减1
        num -= 1;
        goods.setNum(num);

        if (num > -1) {
            //更新商品信息
            int rs = baseMapper.updateById(goods);
            if (rs > 0) {
                //添加订单信息
                rs = orderMapper.saveOrder(id, goodsId);
            }

            System.out.println("用户"+id+"购买了商品"+goodsId);
        }

    }
}
